package com.yupi.yupicturebackend.api.imageSearch.sub;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class GetImagePageUrlApi {
    public static void main(String[] args) {
        // 测试以图搜图功能
//        String imageUrl = "https://b0.bdstatic.com/ugc/BVfjhxryVNA5tsJMO8MneQ42cd37900ba55e9d4d6679f53dd1dc6e.jpg";
        String imageUrl = "https://www.codefather.cn/logo.png";
        String imagePageUrl = getImagePageUrl(imageUrl);
        System.out.println(imagePageUrl);
    }

    /**
     * 获取图片搜索结果页面的url
     * @param imageUrl
     * @return
     */
    public static String getImagePageUrl(String imageUrl){
        // 准备请求参数
        Map<String, Object> formData = new HashMap<>();
        formData.put("image", imageUrl);
        formData.put("tn","pc");
        formData.put("from","pc");
        formData.put("image_source", "PC_UPLOAD_URL");
        // 获取当前时间戳
        long upTime = System.currentTimeMillis();
        // 请求地址
        String url = "https://graph.baidu.com/upload?uptime="+  upTime;
        // 发送POST请求
        try {
            HttpResponse response = HttpRequest.post(url)
                    .header("acs-token", RandomUtil.randomString(1))
                    .form(formData)
                    .timeout(5000)
                    .execute();
            // 判断相应状态
            if (HttpStatus.HTTP_OK != response.getStatus()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "百度以图搜图接口调用失败");
            }
            // 解析响应
            String responseBody = response.body();
            Map<String, Object> result = JSONUtil.toBean(responseBody, Map.class);

            // 处理相应结果
            if(result == null || !Integer.valueOf(0).equals(result.get("status"))){
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "百度以图搜图接口调用失败");
            }
            Map<String, Object> data = (Map<String, Object>)result.get("data");
            String  rawUrl =(String)data.get("url");
            // 对url进行解码
            String searchResultUrl = URLUtil.decode(rawUrl, StandardCharsets.UTF_8);
            // 如果url为空
            if (searchResultUrl == null) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "未返回有效结果");
            }
            return searchResultUrl;
        } catch (Exception e) {
            log.error("百度以图搜图接口调用异常", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"搜索失败");
        }
    }
}
